package com.baseproject.json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by hp on 2017/7/14.
 */

public class GsonProcessor implements IJsonProcessor{

    Gson mGson = new Gson();

    @Override
    public <M> M strToModel(String jsonStr, Class<M> modelClazz) {
        if (modelClazz.getName().equals("org.json.JSONArray")) {
                try {
                    return (M) new JSONArray(jsonStr.substring(jsonStr.indexOf('[')));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
        }
        return mGson.fromJson(jsonStr, modelClazz);
    }

    @Override
    public <M> M strToModel(String jsonStr, Type type) {
        return mGson.fromJson(jsonStr, type);
    }

    @Override
    public <M> String modelToStr(M model) {
        return mGson.toJson(model);
    }

    @Override
    public <M> List<M> strToListModel(String jsonStr, Class<M> modelClazz) {
        Type listType = new TypeToken<List<M>>() {}.getType();
        return mGson.fromJson(jsonStr, listType);
    }

    @Override
    public <M> String listModelToStr(List<M> models) {
        Type listType = new TypeToken<List<M>>() {}.getType();
        return mGson.toJson(models, listType);
    }

}
